<template>
  <div id="">

    <div class="container">
    <div :style="barHeigth" class="cardBox tabsAnimation">
        <div  :class="index==TabCur?'text-blue cur':''" v-for="(item, index) in tabNav" :key="index" @click='tabSelect(index)' style="position:relative;">
          {{item.title}}
          <div class="cu-tag badge" v-if="!item.DotNum==0">{{item.DotNum}}</div>
        </div>
        <text class="cuIcon-delete lg text-purple " @click="deleAll()">清除</text>
    </div>



    <div class="allPage" >
      <block v-if="TabCur==0">
   <div v-for="(item, index) in dynamicMessage.comment" @touchstart="delMessage(index)" >
      <div class="padding-xl  bg-white card newsAnimation" style="position:relative; margin-bottom:20rpx;margin-top:20rpx;" >
      <div class="cu-tag badge" v-if="item.dot==true"></div>
      <div class="timeType">{{item.time}}</div>
        <text class="text-blue" @click="inPersonPage(item.commentOpenid)" >{{item.commentName}}</text>
        回复：<text class="comment-text" @click="navigation(item._id, index)">{{item.comment}} </text>
        <text class="dynamicType"  @click="navigation(item._id, index)" >{{item.content}}</text>
      </div>
  </div>
  <img  src="../../../static/images/empty.png" v-if="!dynamicMessage.comment.length"></img>
      </block>

      <block v-if="TabCur==1">

       <div v-for="(item, index) in dynamicMessage.praise" @touchstart="delMessage(index)">
          <div class="padding-xl bg-white card newsAnimation margin-top" style="position:relative;margin-bottom:20rpx;margin-top:20rpx;">
            <div class="cu-tag badge" v-if="item.dot==true"></div>
            <text class="text-blue" @click="inPersonPage(item.commentOpenid)">{{item.praiserName}}</text>
            刚刚点赞了你
            <text class="timeType" @click="navigation(item._id, index)">
              {{item.time}}</text>
            <text class="dynamicType" @click="navigation(item._id, index)">\n{{item.content}}</text>
          </div>
        </div>
        <img  src="../../../static/images/empty.png" v-if="!dynamicMessage.praise.length"></img>
      </block>


     <!-- 系统消息 -->
        <block v-if="TabCur==2">

          <div v-for="(item,index) in dynamicMessage.system" :key="index">
            <div class="padding-xl bg-white card newsAnimation" @click="inMessagePage(index)"
              @touchstart="delMessage(index)">
              <div class="cu-tag badge" v-if="item.dot==true"></div>
              <text class="text-blue" >{{item.title}}</text>
              <text class="timeType"> {{item.time}}</text>
              <text class="systemType">\n{{item.content}}</text>
            </div>
            <img  src="../../../static/images/empty.png" v-if="!dynamicMessage.system.length"></img>
          </div>
        </block>





    </div>
    </div>
  </div>
</template>

<script>
  import custom from '@/components/custom'
  import tools from "../../utils/filter"
  const db = wx.cloud.database()
  const app = getApp()
  var ret = {};//新增，保存从动态详情页返回后的对应动态的点赞状态和数量
  var listLenFind = 0; //新增，记录关注动态列表的长度

  export default{
    data(){
      return{
         index: 0,
            TabCur: 0,
            tabNav: [{title:'评论',DotNum:0},{title:'点赞',DotNum:0},{title:'系统',DotNum:0}],
            dynamicMessage:[],
            CustomBar:'',
            commentDotNum:0,
            praiseDotNum:0,
            systemDotNum:0,
            flag:false, //判断用户是否登陆
            PrivateDotNum:0,    //私信新增
            openid:"",
      }
    },
    created() {
          let that=this;
          that.CheckIfLogin()

          this.openid = wx.getStorageSync('openid');

    },
     onReady: function () {
      },
      onShow: function () {
        let that=this;
        // this.tabBar()
        this.CheckIfLogin()
        if(app.ifLogin)
        {
          that.getMessage()
        }
        else
        {
          that.loginWindow()
        }
      },
      onHide: function () {
      },
      onUnload: function () {
      },
      onPullDownRefresh: function () {//有改动
        wx.stopPullDownRefresh({})
        wx.showToast({
          title: '刷新成功',
          icon: 'none',
          duration: 800
        })
      },
      //页面上拉触底事件的处理函数
      onReachBottom: function () {

      },
    methods:{

      //检查是否已经登陆
       CheckIfLogin() {
        if(wx.getStorageSync('userInformation')!= undefined){
          app.ifLogin=true
        }
        else{
          this.loginWindow()
        }
      },
      //登陆弹窗
      loginWindow()
      {
        wx.showModal({
          title:'提示',
          content:'登陆后查看消息，是否登陆？',
          success (res) {
           if (res.confirm) {
            wx.navigateTo({
              url: '../login/login',
            })
           } else if (res.cancel) {
            app.ifLogin = false
           }
          }
         })
      },
        tabSelect(e) {
          console.log(e)
           this.index = e;
           this.TabCur = e;
        },
        //获取所有消息
        getMessage(){
          var that=this;
          db.collection('message').where({
            _openid:wx.getStorageSync('openid')
          })
          .get()
          .then(async res=>{
              that.dynamicMessage = res.data[0],
              console.log("res.data[0]", res.data[0])
              that.changTime(res.data[0]);
              await that.countCommentDots(res.data[0])

          })

        },
        changTime(data){
          for(let i = 0; i<data.comment.length; i++){
            data.comment[i].time = tools.timeChn(data.comment[i].time);
          }
          for(let i = 0; i<data.praise.length; i++){
            data.praise[i].time = tools.timeChn(data.praise[i].time);
          }
        },
        //计算未读消息数量
       async countCommentDots(message){
        var commentDotNum=0
        var praiseDotNum=0
        var systemDotNum=0
        var i=0
        for(i=0;i<message.comment.length;i++)
        {
           if(message.comment[i].dot)
           {
            commentDotNum=commentDotNum+1
           }
        }
        for(i=0;i<message.praise.length;i++)
        {
           if(message.praise[i].dot)
           {
            praiseDotNum=praiseDotNum+1
           }
        }
        for(i=0;i<message.system.length;i++)
        {
           if(message.system[i].dot)
           {
            systemDotNum=systemDotNum+1
           }
        }
          this.tabNav = [{title:'评论',DotNum:commentDotNum},{title:'点赞',DotNum:praiseDotNum},{title:'系统',DotNum:systemDotNum}];
          let allDots = commentDotNum + praiseDotNum + systemDotNum;
         wx.setStorageSync('dotsNum', allDots.toString())
         if(wx.getStorageSync('dotsNum'))
         {
           if(wx.getStorageSync('dotsNum')!='0')
           {
            wx.setTabBarBadge({
              index: 2,
              text: wx.getStorageSync('dotsNum')
            })
           }
           else
           {
             wx.removeTabBarBadge({
               index: 2,
             })
           }
         }
        },
        //清除所有消息
        deleAll()
        {
          let that = this;
          let event = [
            {"title" :"评论", table:"comment"},
            {"title" :"点赞", table:"praise"},
            {"title" :"系统", table:"system"},
          ]
          let index = this.TabCur;
          let table = {}
          table[event[index].table] =[];

            wx.showModal({
              title:'提示',
              content:'确定要清空' + event[index].title + '评论消息列表？',
              success (res) {
               if (res.confirm) {
                 db.collection("message").where({
                   _openid:wx.getStorageSync('openid')
                 })
                 .update({
                     data:table
                   }).then(res=>{
                     wx.showToast({
                       title: '已清空！',
                     })
                     that.getMessage();
                   })
               } else if (res.cancel) {
               }
              }
             })

        },

        //删除消息
         delMessage(index){
          var that=this;
          let event = ["comment","praise","system"];
          let table = event[this.TabCur] //板块对应的字段
            wx.showModal({
              title:'提示',
              content:'确定要删除此消息？',
              success (res) {
               if (res.confirm) {
                 db.collection("message")
                 .where({
                   _openid:wx.getStorageSync('openid')
                 })
                 .get()
                 .then(res=>{

                   var message=res.data[0][table];
                   message.splice(index,1)
                   let updateMessage = {}
                   updateMessage[table] = message

                   db.collection("message").doc(res.data[0]._id).update({
                     data:updateMessage
                   }).then(res=>{
                     wx.showToast({
                       title: '删除成功！',
                     })
                     that.getMessage();
                   })

                 })
               } else if (res.cancel) {
               }
              }
             })

          },
        //进入详情页
        inMessagePage(e){
          var index=e.currentTarget.dataset.index
          this.changeSystemDot(index)
          var message=JSON.stringify(this.data.dynamicMessage.system[index]);
          wx.navigateTo({
            url: '../message/messagePage/messagePage?message='+message,
          })
        },

        //改变提示阅读的红点状态(点赞)
        changePraiseDot(index){
        db.collection('message')
        .where({
          _openid:wx.getStorageSync('openid'),
        })
        .update({
          data:{
            praise:{
              [index]:{
                dot:false
              }
            }
          }
        })
        .then(res=>{
        })
        },
        //改变提示阅读的红点状态(评论)
        changeMessageDot(index){
          db.collection('message')
        .where({
          _openid:wx.getStorageSync('openid'),
        })
        .update({
          data:{
            comment:{
              [index]:{
                dot:false
              }
            }
          }
        })
        .then(res=>{
        })
          },
        //改变提示阅读的红点状态(系统消息)
        changeSystemDot(index){
          db.collection('message')
        .where({
          _openid:wx.getStorageSync('openid'),
        })
        .update({
          data:{
            system:{
              [index]:{
                dot:false
              }
            }
          }
        })
        .then(res=>{
        })
          },


        //进入个人主页
        inPersonPage(e){
          wx.navigateTo({
            url: '../personPage/personPage?openid=' + e.currentTarget.dataset.openid,
          })
        },
        //进入动态详情页
        async navigation(e){
          var content={};

          if(this.data.TabCur==0)
          {
          this.changeMessageDot(e.currentTarget.dataset.index)
          var contentId=this.data.dynamicMessage.comment[e.currentTarget.dataset.index].contentId
          try {
            await db.collection('dynamic').doc(contentId)
            .get()
            .then( res=>{
              content= res.data
            })
            var connent=JSON.stringify(content);
            wx.navigateTo({
              url: '../detailPage/detailPage?id=' + contentId +"&connent="+connent,
            })
          }
          catch (error)
          {
           wx.showToast({
             title: '该动态已不存在',
             icon:'none',
             duration: 2000
           })
          }

          }
          if(this.TabCur==1)
          {
          this.changePraiseDot(e.currentTarget.dataset.index)
          var contentId=this.data.dynamicMessage.praise[e.currentTarget.dataset.index].dynamicId

           try {
            await db.collection('dynamic').doc(contentId)
            .get()
            .then( res=>{
              content= res.data
            })
            var connent=JSON.stringify(content);
            wx.navigateTo({
              url: '../detailPage/detailPage?id=' + contentId +"&connent="+connent,
            })
          }
          catch (error)
          {
           wx.showToast({
             title: '该动态已不存在',
             icon:'none',
             duration: 2000
           })
          }

          }

        },

    },
    components:{
      custom,
    },
    computed:{
      barHeigth(){
        return 'width: 95%;height: 45px;position: fixed;z-index: 99999;';
      },
    },

  }
</script>

<style scoped>
  .container {
    height: 100vh;
    background-color: #F8F8FF;

  }
  .cardBox {
    box-shadow:  0rpx 0rpx 7rpx 0 #A9A9B4;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    overflow: hidden;
    border-radius: 30rpx;
    margin-bottom: 10rpx;
    background-color: white;
  }
  .card {
    box-shadow:  0rpx 0rpx 7rpx 0 #A9A9B4;
    border-radius: 25rpx;
    margin-left: 20rpx;
    margin-right: 20rpx;
    margin-top: 20rpx;
  }
  .allPage {
    width: 94%;
    height: auto;
    background-color: #F8F8FF;
    position: relative;
    top: 130rpx;
    margin-bottom: 180rpx;
  }
  .bar {
    position: relative;
    top: 64rpx;
  }
  .margin-top {
    margin-top: 10rpx;
  }
  .padding-xl {
    padding: 25px 20px;
  }
  .shadow[class*='white'] {
    --ShadowSize: 0 0rpx 2rpx;
  }
  .timeType {
    margin-top: 3rpx;
    position: relative;
    float: right;
    color: gray;
    font-size: 10px;
  }
  .dynamicType {
    position: relative;
    top: 0px;
    font-size: 13px;
    color: grey;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  .systemType {
    position: relative;
    top: 0px;
    font-size: 13px;
    line-height: 23px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
  }

  .deleteBtn {
    position: relative;
    top: 13px;
    left: 20px;
    float: left;
    width: 0px;
  }

  .tabsAnimation {
    animation: zoomIn 1.5s 1
  }

  .newsAnimation {
    animation: fadeInUp 2s 1;
  }

  .messageAndPraise {
    margin: 10px 10px;
  }
.cur {
	border-bottom: 4rpx solid;
}
.badge {
    border-radius: 200rpx;
    position: absolute;
    top: -10rpx;
    right: -45rpx;
    font-size: 20rpx;
    padding: 0rpx 10rpx;
    height: 28rpx;
    color: var(--white);
}
.comment-text{
    display: inline-block;
    margin-right: 60rpx;
}
</style>
